import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Affix, Modal, Table, Checkbox, Input, Select, message, Icon, Tabs, Alert } from 'antd';
import styles from '../../index.less';
import * as config from '../../utils/config';

const { Option } = Select;
const { TabPane } = Tabs;

class AffixMenuComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      top: 10,
      modalPanel: { title: '用户个性化配置' },
      modalVisible: false,
      modalData: [],
      modalContent: [], /* 面板展示内容 */
      modalContentData1: [],
      modalContentData2: [],
      modalContentData3: [],
      modalContentData4: [],
      modalContentData5: [],
      modalContentData6: [],
      modalContentData7: [],
      modalContentData8: [],
      modalContentData9: [],
      modalContentData10: [],
      roleShow: '', /* 角色 */
      roleSelectData: '', /* 选择的角色 */
    };
  }
  componentDidMount() {
    const sActiveId = this.props.app.currentPane.formId;
    const url = `${config.server_host}configform//getConfigformData/${sActiveId}?sModelsId=${sActiveId}`;
    const { token } = this.props.app;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const data = json.dataset.rows[0];
        this.setState({ modalData: data });
        let count = 1;
        Object.keys(data).forEach((child) => {
          /* 数据增加key属性用于table展示 */
          for (const item of data[child]) {
            item.key = item.sId;
          }
          this.setState({ [`modalContentData${count}`]: data[child] });
          count += 1;
        });
      } else {
        console.log(json.msg);
      }
    });

    if (this.props.app.userinfo.sType === 'sysadmin') {
      const roleUrl = `${config.server_host}configform/getLogininfosupplygroup?sModelsId=${sActiveId}`;
      /* 获取角色下拉 */
      fetch(roleUrl, options).then(response => response.json()).then((json) => {
        if (json.code === 1) {
          const data = json.dataset.rows;
          const oPtinon = [];
          for (const child of data) {
            oPtinon.push(<Option key={child.sId} value={child.sId}>{child.sName}</Option>);
          }
          const roleShow = (
            <Alert
              message={(
                <div className={styles.affixMenuShow}>
                  <span>选择角色</span>
                  <Select
                    style={{ width: 180 }}
                    filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={e => this.handleSelectChange(e)}
                    placeholder="请选择一个角色"
                  >
                    {oPtinon}
                  </Select>
                </div>

              )}
              type="info"
              showIcon
            />
          );
          this.setState({ roleShow });
        } else {
          console.log(json.msg);
        }
      });
    }
  }

  handleClick=() => {
    this.setState({ modalVisible: true });
  };

  handlePpopUpPaneCancel=() => {
    this.setState({ modalVisible: false });
  };

  handleChange=(value, count, record, name) => {
    const data = JSON.parse(JSON.stringify(this.state[`modalContentData${count}`]));
    const dataMap = data.filter(item => (item.key === record.key))[0];
    if (dataMap !== undefined) {
      dataMap[`${name}`] = value;
    }
    this.setState({ [`modalContentData${count}`]: data });
  };

  handleSelectChange=(value) => {
    this.setState({ roleSelectData: value });
  };

  handleOk=() => {
    const sActiveId = this.props.app.currentPane.formId;
    const url = `${config.server_host}configform/sHandleConfigform?sModelsId=${sActiveId}`;
    const { token } = this.props.app;
    const { roleShow, roleSelectData } = this.state;
    if (roleShow !== '' && roleSelectData === '') {
      message.warning('请选择角色');
      return;
    }
    const submitData = {};
    let count = 1;
    let num = 0;
    while (count <= 10) {
      if (this.state[`modalContentData${count}`].length > 0) {
        num = 0;
        for (const child of this.state[`modalContentData${count}`]) {
          if (num === 0) {
            submitData[`${child.sParentId}`] = [];
          }
          if (child.bVisible) {
            submitData[`${child.sParentId}`].push(child);
          }
          num += 1;
        }
      }
      count += 1;
    }
    let value = '';
    if (roleShow !== '') {
      value = {
        handleType: 'group',
        sJurisdictionClassifyId: roleSelectData,
        handleData: submitData,
      };
    } else {
      value = {
        handleType: 'user',
        handleData: submitData,
      };
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);
        this.handlePpopUpPaneCancel();
      }
    });
  };

  renderColumns=(text, name, count, record) => {
    if (name === 'bVisible') {
      return <Checkbox defaultChecked={text} checked={text} onChange={e => this.handleChange(e.target.checked, count + 1, record, name)} />;
    } else {
      return <Input value={text} onChange={e => this.handleChange(e.target.value, count + 1, record, name)} />;
    }
  };

  render() {
    const { modalData, roleShow } = this.state;
    const modalContent = [];
    let count = 1;
    Object.keys(modalData).forEach((child, i) => {
      let childTable = '';
      const columns = [{
        title: '排序',
        dataIndex: 'iOrder',
        render: (text, record) => this.renderColumns(text, 'iOrder', i, record),
        width: 80,
      }, {
        title: '显示名',
        dataIndex: 'showName',
        render: (text, record) => this.renderColumns(text, 'showName', i, record),
        width: 200,
      }, {
        title: '宽度',
        dataIndex: 'iFitWidth',
        render: (text, record) => this.renderColumns(text, 'iFitWidth', i, record),
        width: 80,
      }, {
        title: '是否显示',
        dataIndex: 'bVisible',
        render: (text, record) => this.renderColumns(text, 'bVisible', i, record),
        width: 90,
      }];
      childTable = (
        <TabPane tab={child} key={count}>
          <div key={count} className={styles.affixMenuTableAll}>
            <Table
              bordered
              columns={columns}
              dataSource={this.state[`modalContentData${count}`]}
              pagination={false}
              scroll={{ y: 310 }}
              className={styles.affixMenuTable}
            />
          </div>
        </TabPane>
      );
      modalContent.push(childTable);
      count += 1;
    });
    return (
      <div>
        <Affix offsetTop={this.state.top} style={{ position: 'absolute', top: 50, left: 1000 }}>
          <div className={styles.affixMenu}>
            <Icon type="setting" onClick={this.handleClick.bind(this)} />
          </div>
          <Modal
            title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
            visible={this.state.modalVisible}
            onCancel={this.handlePpopUpPaneCancel.bind(this)}
            onOk={this.handleOk.bind(this)}
            width={1000}
          >
            <div className={styles.modalsContent}>
              {
                roleShow !== '' ? roleShow : ''
              }
              <div id="slaveTabs">
                <Tabs className={styles.slaveTabs}>
                  {modalContent}
                </Tabs>
              </div>
            </div>
          </Modal>
        </Affix>
      </div>
    );
  }
}

export default AffixMenuComponent;
